package com.yj.lottery_system.common.utils;

import cn.hutool.extra.mail.MailUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Random;

@Slf4j
@Component
@RequiredArgsConstructor
@Data
public class EmailCodeUtil {


    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${mail.code.length:6}")
    private int codeLength;

    /**
     * 发送邮件
     * @param to
     * @param subject
     * @param context
     * @return
     */
    public Boolean sendSampleMail(String to, String subject, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return false;
        }
        return true;
    }


    /**
     * 发送「纯数字验证码」到邮箱
     * 语义保持与原来 SMSUtil.sendMessage 一致，方便替换
     *
     * @param templateCode 此处无实际意义，保留参数避免调用方改动
     * @param mailAddress  接收验证码的邮箱
     * @param templateParam 留空即可（原短信模板参数用不到）
     * @return 生成的验证码（调用方可选择缓存）
     */
    public String sendMessage(String templateCode, String mailAddress, String templateParam) {
        String code = generateCode(codeLength);
        try {
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(from);
            msg.setTo(mailAddress);
            msg.setSubject("验证码");
            msg.setText("您的验证码为：" + code + "，" + codeLength + "位数字，1分钟内有效，请勿泄露。");
            mailSender.send(msg);
            log.info("向{}发送验证码成功，code={}", mailAddress, code);
        } catch (Exception e) {
            log.error("向{}发送验证码失败", mailAddress, e);
            throw new RuntimeException("邮件发送失败");
        }
        return code;   // 调用方可自行缓存到 Redis / Session
    }

    /* 生成 length 位纯数字随机码 */
    private String generateCode(int length) {
        int bound = (int) Math.pow(10, length);
        return String.format("%0" + length + "d", new Random().nextInt(bound));
    }

    /* 可选：快速发送方法，只传邮箱 */
    public String sendCode(String mailAddress) {
        return sendMessage(null, mailAddress, null);
    }
    /**
     * 发送「指定验证码」到邮箱（不再重新生成）
     */
    public void sendFixedCode(String mailAddress, String code) {
        try {
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(from);
            msg.setTo(mailAddress);
            msg.setSubject("验证码");
            msg.setText("您的验证码为：" + code + "，4位数字，请勿泄露。");
            mailSender.send(msg);
            log.info("向{}发送固定验证码成功，code={}", mailAddress, code);
        } catch (Exception e) {
            log.error("向 {} 发送验证码异常", mailAddress, e);  // 带堆栈
            throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
        }
    }
}